﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using MaxStudio.Concrete.Web;
using MaxStudio.Concrete.DBUtility;
using MaxStudio.Concrete.Server;
using MaxStudio.Concrete.Server.Service;
using MaxStudio.Concrete.Server.Dao;
using MaxStudio.Concrete.Component;

namespace MaxStudio.Concrete.Web.Pages
{
    public partial class Receivable : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGridView();

                WebPartBind.BindMasterDataDDL(this.ddlStatus, Int32.Parse(System.Configuration.ConfigurationSettings.AppSettings["MDReceivableStatus"].ToString()));
                WebPartBind.BindMasterDataDDL(this.ddlReceivableType, Int32.Parse(System.Configuration.ConfigurationSettings.AppSettings["MDPayType"].ToString()));
                WebPartBind.BindTrackingDDL(this.ddlTraker);
                BindContract();
            }
        }

        #region Private Method  

        private void BindContract()
        {
            SalesOrderService salesorderServiceObj = ServiceFactory.getSalesOrderServices();
            OperationResult<List<tb_SalesOrder>> list = salesorderServiceObj.GetAllSalesOrder();

            if (list.operationSuccess)
            {
                ddlContranctId.DataSource = list.obj;
                ddlContranctId.DataTextField = "ContranctSN";
                ddlContranctId.DataValueField = "Id";
                ddlContranctId.DataBind();
            }
        }

        private void BindEditContract()
        {
            SalesOrderService salesorderServiceObj = ServiceFactory.getSalesOrderServices();
            OperationResult<List<tb_SalesOrder>> list = salesorderServiceObj.GetAllSalesOrder();

            if (list.operationSuccess)
            {
                ddlEditContranctId.DataSource = list.obj;
                ddlEditContranctId.DataTextField = "ContranctSN";
                ddlEditContranctId.DataValueField = "Id";
                ddlEditContranctId.DataBind();
            }
        }

        private void BindGridView()
        {
            ReceivableService receivableServiceObj = ServiceFactory.getReceivableService();
            OperationResult<List<tb_Receivable>> result = receivableServiceObj.GetAllReceivable();

            if (result.operationSuccess)
            {
                gvReceivableList.DataSource = result.obj;
                gvReceivableList.DataBind();
            }
            else
            {
                //EXCEPTION
                //return null;
            }
        }

        private void BindEdieDialog(int id)
        {
            WebPartBind.BindMasterDataDDL(this.ddlEditStatus, Int32.Parse(System.Configuration.ConfigurationSettings.AppSettings["MDReceivableStatus"].ToString()));
            WebPartBind.BindTrackingDDL(this.ddlEditTraker);
            BindEditContract();
            ReceivableService receivableServiceObj = ServiceFactory.getReceivableService();
            OperationResult<tb_Receivable> resultEdit = receivableServiceObj.GetReceivableById(id);
            if (resultEdit.operationSuccess == true)
            {
                ddlEditContranctId.SelectedValue = resultEdit.obj.ContranctId.ToString();
                ddlEditHaveBill.SelectedValue = resultEdit.obj.HaveBill.ToString();
                txtEditAmount.Text = resultEdit.obj.Amount.ToString();
                ddlEditTraker.SelectedValue = resultEdit.obj.Traker.ToString();
                ddlEditRound.SelectedValue = resultEdit.obj.Round;
                ddlEditStatus.SelectedValue = resultEdit.obj.Status.ToString();
                txtEditDescription.Text = resultEdit.obj.Description;

                lbLastModier.Text = "TEST";
                lbEidtId.Text = resultEdit.obj.Id.ToString();
                lbLastModifyDate.Text = resultEdit.obj.ModifyDate.ToShortDateString();
            }
        }

        private void DeleteRecords(int id)
        {
            lbDeleteId.Text = id.ToString();
        } 
      
        public string GetUserNameById(string strUserId)
        {
            int userId = Int32.Parse(strUserId);
            return MasterDateString.GetUserNameById(userId);
        }
        public string GetMasterDataNameById(string strTypeId)
        {
            int masterDataId = Int32.Parse(strTypeId);
            return MasterDateString.GetMasterDataNameById(masterDataId);
        }

        private void BindDetails(int id)
        {
            lblReceivableId.Text = id.ToString();

        }

        private void BindCheckshouldGetList(int id)
        {
            lblDeleteReceivableId.Text = id.ToString();
            int intReceivableId = Int32.Parse(id.ToString());

            ReceivableDetailsService detailsServiceObj = ServiceFactory.getReceivableDetailsService();
            OperationResult<List<tb_ReceivableDetail>> result = detailsServiceObj.GetReceivableDetailsByReceivableId(intReceivableId);
            if (result.operationSuccess == true)
            {
                gvReceivableDetailsList.DataSource = result.obj;
                gvReceivableDetailsList.DataBind();
            }

        }

        private void BindReceivableDetailsList()
        {
            // TODO  current set the page size is 999.
        }  

        protected void DeleteReceivableDetailsRecords(int id)
        {
            ReceivableDetailsService receivableDetailsServiceObj = ServiceFactory.getReceivableDetailsService();
            tb_ReceivableDetail deleteEntity = new tb_ReceivableDetail();
            deleteEntity.Id = id;
            receivableDetailsServiceObj.DeleteReceivableDetails(deleteEntity);
            BindCheckshouldGetList(Int32.Parse( lblDeleteReceivableId.Text));
        }

        public string CalculatorReceivable(string strReceivableId)
        {
            int receivableId = Int32.Parse(strReceivableId);
            ReceivableService receivableServiceObj = ServiceFactory.getReceivableService();
            OperationResult<tb_Receivable> receivableResult = receivableServiceObj.GetReceivableById(receivableId);
            tb_Receivable receivableEntity = new tb_Receivable();
            if (receivableResult.operationSuccess)
            {
                receivableEntity = receivableResult.obj;
            }
            decimal totalAmount = receivableEntity.Amount;

            List<tb_ReceivableDetail> DetailsList = new List<tb_ReceivableDetail>();
            ReceivableDetailsService receivableDetailsServiceObj = ServiceFactory.getReceivableDetailsService();
            OperationResult<List<tb_ReceivableDetail>> DetailsListResult = receivableDetailsServiceObj.GetReceivableDetailsByReceivableId(receivableId);
            if (DetailsListResult.operationSuccess)
            {
                DetailsList = DetailsListResult.obj;
            }
            decimal receivableAmount = 0;

            foreach (tb_ReceivableDetail entity in DetailsList)
            {
                receivableAmount = receivableAmount + entity.Amount;
            }

            return receivableAmount.ToString();
        }
        public string CalculatorNotReceivable(string strReceivableId)
        {
            int receivableId = Int32.Parse(strReceivableId);
            ReceivableService receivableServiceObj = ServiceFactory.getReceivableService();
            OperationResult<tb_Receivable> receivableResult = receivableServiceObj.GetReceivableById(receivableId);
            tb_Receivable receivableEntity = new tb_Receivable();
            if (receivableResult.operationSuccess)
            {
                receivableEntity = receivableResult.obj;
            }
            decimal totalAmount = receivableEntity.Amount;

            List<tb_ReceivableDetail> DetailsList = new List<tb_ReceivableDetail>();
            ReceivableDetailsService receivableDetailsServiceObj = ServiceFactory.getReceivableDetailsService();
            OperationResult<List<tb_ReceivableDetail>> DetailsListResult = receivableDetailsServiceObj.GetReceivableDetailsByReceivableId(receivableId);
            if (DetailsListResult.operationSuccess)
            {
                DetailsList = DetailsListResult.obj;
            }
            decimal receivableAmount = 0;

            foreach (tb_ReceivableDetail entity in DetailsList)
            {
                receivableAmount = receivableAmount + entity.Amount;
            }

            decimal notReceivable = totalAmount - receivableAmount;
            return notReceivable.ToString();
        }
        #endregion

        #region Event
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            ReceivableService receivableServiceObj = ServiceFactory.getReceivableService();
            tb_Receivable instance = new tb_Receivable();

            instance.ContranctId = Int32.Parse(ddlContranctId.SelectedValue);
            instance.HaveBill = Int32.Parse(ddlHaveBill.SelectedValue);
            instance.Amount = decimal.Parse(txtAmount.Text);
            instance.Traker = Int32.Parse(ddlTraker.SelectedValue);
            instance.Round = ddlRound.SelectedValue;
            instance.Status = Int32.Parse(ddlStatus.SelectedValue);
            instance.Description = txtDescription.Text;

            OperationResult<tb_Receivable> result = receivableServiceObj.CreateReceivable(instance);
            BindGridView();
        }
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            int editId = 0;
            if (lbEidtId.Text.Length > 0)
            {
                editId = Int32.Parse(lbEidtId.Text);
            }

            ReceivableService receivableServiceObj = ServiceFactory.getReceivableService();
            tb_Receivable entity = new tb_Receivable();

            entity.Id = editId;

            entity.ContranctId = Int32.Parse(ddlEditContranctId.SelectedValue);
            entity.HaveBill = Int32.Parse(ddlEditHaveBill.SelectedValue);
            entity.Amount = decimal.Parse(txtEditAmount.Text);
            entity.Traker = Int32.Parse(ddlEditTraker.SelectedValue);
            entity.Round = ddlEditRound.SelectedValue;
            entity.Status = Int32.Parse(ddlEditStatus.SelectedValue);
            entity.Description = txtEditDescription.Text;
             
            entity.ModifyDate = DateTime.Now;
            entity.ModifyBy = 1;
            entity.CreateDate = DateTime.Now;

            OperationResult<tb_Receivable> resultEdit = receivableServiceObj.ModifyReceivable(entity);
            BindGridView();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            int deleteId = Int32.Parse(lbDeleteId.Text);
            ReceivableService receivableServiceObj = ServiceFactory.getReceivableService();
            tb_Receivable deleteEntity = new tb_Receivable();
            deleteEntity.Id = deleteId;

            try
            {
                receivableServiceObj.DeleteReceivable(deleteEntity);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            BindGridView();
        } 

        protected void gvReceivableList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                string strSelectId = e.CommandArgument.ToString();
                BindEdieDialog(Int32.Parse(strSelectId));
            }

            if (e.CommandName == "del")
            {
                string strSelectId = e.CommandArgument.ToString();
                DeleteRecords(Int32.Parse(strSelectId));
            }
            if (e.CommandName == "AddDetails")
            {
                string strSelectId = e.CommandArgument.ToString();
                BindDetails(Int32.Parse(strSelectId));
            }

            if (e.CommandName == "CheckshouldGetList")
            {
                string strSelectId = e.CommandArgument.ToString();
                BindCheckshouldGetList(Int32.Parse(strSelectId));
            }

        }

        protected void gvReceivableList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvReceivableList.PageIndex = e.NewPageIndex;
            BindGridView();
        } 

        protected void gvReceivableDetailsList_RowCommand(object sender, GridViewCommandEventArgs e)
        { 
            if (e.CommandName == "del")
            {
                string strSelectId = e.CommandArgument.ToString();
                DeleteReceivableDetailsRecords(Int32.Parse(strSelectId));
            }
        }

        protected void gvReceivableDetailsList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvReceivableDetailsList.PageIndex = e.NewPageIndex;
            BindReceivableDetailsList();
        }


        protected void btnSubmitDetails_Click(object sender, EventArgs e)
        {
            int intReceivableId = Int32.Parse(lblReceivableId.Text);
            int intReceivableType = Int32.Parse(ddlReceivableType.SelectedValue);
            decimal decimalAmount = decimal.Parse(txtReceivableDetailsAmount.Text);

            tb_ReceivableDetail DetailsEntity=new tb_ReceivableDetail ();
            DetailsEntity.ReceivableId=intReceivableId;
            DetailsEntity.ReceivableType=intReceivableType;
            DetailsEntity.Amount=decimalAmount;

            ReceivableDetailsService receivableServiceObj = ServiceFactory.getReceivableDetailsService();

            OperationResult<tb_ReceivableDetail> result = receivableServiceObj.CreateReceivableDetails(DetailsEntity);            

        }

        #endregion

        
    }
}
